// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// o [author] rhyme_lph
// B [email]  rhymelph@gmail.com
// a [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/cpf_contribution_entity.dart';
import 'package:finance_app/src/provider/hr_payroll/payroll/record_cpf_contribution_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/input_formatter_tools.dart';
import 'package:finance_app/src/widgets/button/normal_border_button.dart';
import 'package:finance_app/src/widgets/button/normal_popup_button.dart';
import 'package:finance_app/src/widgets/button/normal_text_button.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/form/form_edit_status_inherited_widget.dart';
import 'package:finance_app/src/widgets/input/cpf_donor_input_field.dart';
import 'package:finance_app/src/widgets/input/cpf_input_field.dart';
import 'package:finance_app/src/widgets/list_item/time_select_item.dart';
import 'package:flutter/material.dart';
import 'package:tuple/tuple.dart';

@RouterMeta(paramName: "recordCpfContributionPage")
class RecordCpfContributionPage extends StatefulWidget {
  final CpfContributionEntity data;

  const RecordCpfContributionPage({Key key, this.data}) : super(key: key);

  @override
  _RecordCpfContributionPageState createState() =>
      _RecordCpfContributionPageState();
}

class _RecordCpfContributionPageState extends State<RecordCpfContributionPage>
    with
        PagePresenter<RecordCpfContributionPage,
            RecordCpfContributionProvider> {
  String get title => provider.data == null && pageStatus != PageStatus.loading
      ? S.current.new_cpf_contribution
      : provider.isEdit == true
          ? S.current.edit_cpf_contribution
          : S.current.cpf_contribution;

  Widget get rightButton => listBuilder<bool>(
        selector: (_, __) => (__.isEdit == true || provider.data?.id == null),
        builder: (BuildContext context, bool value, Widget child) =>
            value ? _buildSaveBtn() : _buildPopButton(),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
          titleWidget: listBuilder<Tuple2<CpfContributionEntity, bool>>(
            selector: (_, __) => Tuple2(__.data, __.isEdit),
            builder: (BuildContext context,
                    Tuple2<CpfContributionEntity, bool> value, Widget child) =>
                Text(title),
          ),
          actions: [
            rightButton,
          ]);

  @override
  void initState() {
    provider.data = widget.data;
    super.initState();
  }

  Widget _buildPopButton() => listBuilder<Tuple2<bool, List<String>>>(
        selector: (_, __) => Tuple2(!__.isEdit, List.from(__.menuList)),
        builder: (BuildContext context, Tuple2<bool, List<String>> value,
                Widget child) =>
            value.item1
                ? NormalMorePopupButton(
                    onSelect: provider.onSelectMenu,
                    menuList: provider.menuList,
                  )
                : Container(),
      );

  Widget _buildSaveBtn() {
    return listBuilder<bool>(
      selector: (_, __) => pageStatus != PageStatus.loading,
      builder: (BuildContext context, bool value, Widget child) => value == true
          ? NormalSaveTextButton(
              onTap: provider.onSave,
            )
          : Container(),
    );
  }

  @override
  Widget wrapperBody(Widget child) {
    return listBuilder<bool>(
        selector: (_, __) => __.isEdit == true || provider.data?.id == null,
        builder: (BuildContext context, bool value, Widget child) =>
            FormEditStatusInheritedWidget(
              isEdit: value,
              child: child,
            ),
        child: child);
  }

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            AppSpaces.h20,
            _buildYearMonthWidget(),
            AppSpaces.h20,
            Divider(height: getDp(0), color: aceGrayColor, thickness: 0.5),
            Expanded(
              child: ListView(
                children: [
                  _buildCPFTotal(),
                  CpfInputField(
                    title: S.current.employer_cpf,
                    hintText: '0',
                    level: 2,
                    controller: provider.employerCpfController,
                    inputFormatters: [intInputFormatter],
                  ),
                  CpfInputField(
                    title: S.current.employee_cpf,
                    hintText: '0',
                    level: 2,
                    controller: provider.employeeCpfController,
                    inputFormatters: [intInputFormatter],
                  ),
                  CpfInputField(
                    title: S.current.cpf_late_payment_interest,
                    hasBottomBorder: false,
                    controller: provider.cpfLateController,
                  ),
                  AppSpaces.grayH6,
                  CpfInputField(
                    title: S.current.foreign_worker_levy_fwl,
                    controller: provider.fwlController,
                  ),
                  CpfInputField(
                    title: S.current.fwl_late_payment_interest,
                    controller: provider.fwlLateController,
                  ),
                  CpfInputField(
                    title: S.current.skills_development_levt_sdl,
                    hasBottomBorder: false,
                    controller: provider.sdlController,
                  ),
                  AppSpaces.grayH6,
                  CpfInputField(
                    title: S.current.community_chest_donation,
                    controller: provider.communityController,
                  ),
                  CpfDonorInputField(
                    controller: provider.communityDonorController,
                  ),
                  CpfInputField(
                    title: S.current.mbmf_contributions,
                    controller: provider.mbmfController,
                  ),
                  CpfDonorInputField(
                    controller: provider.mbmfDonorController,
                  ),
                  CpfInputField(
                    title: S.current.sinda_contributions,
                    controller: provider.sindaController,
                  ),
                  CpfDonorInputField(
                    controller: provider.sindaDonorController,
                  ),
                  CpfInputField(
                    title: S.current.cdac_contribution,
                    controller: provider.cdacController,
                  ),
                  CpfDonorInputField(
                    controller: provider.cdacDonorController,
                  ),
                  CpfInputField(
                    title: S.current.ecf_contributions,
                    controller: provider.ecfController,
                  ),
                  CpfDonorInputField(
                    hasBottomBorder: false,
                    controller: provider.ecfDonorController,
                  ),
                  AppSpaces.grayH6,
                  _buildGrandTotal(),
                  listBuilder<bool>(
                    selector: (_, __) =>
                        __.menuList.contains("Record Payment") &&
                        __.data.status != 'closed' &&
                        __.data?.id != null &&
                        !__.isEdit,
                    builder: (BuildContext context, bool value, Widget child) =>
                        Column(
                      children: [
                        if (value)
                          Padding(
                            padding: EdgeInsets.only(top: getDp(30)),
                            child: NormalBorderButton(
                              title: S.current.record_payment,
                              onTap: provider.onRecordPayment,
                              isFit: true,
                            ),
                          ),
                      ],
                    ),
                  ),
                  listBuilder<bool>(
                    selector: (_, __) =>
                        __.menuList.contains("See Payment") &&
                        __.data.status == 'closed' &&
                        __.data?.id != null &&
                        !__.isEdit,
                    builder: (BuildContext context, bool value, Widget child) =>
                        Column(
                      children: [
                        if (value)
                          Padding(
                            padding: EdgeInsets.only(top: getDp(30)),
                            child: NormalBorderButton(
                              title: S.current.see_payment,
                              onTap: provider.onSeePayment,
                              isFit: true,
                            ),
                          ),
                      ],
                    ),
                  ),
                  AppSpaces.h50
                ],
              ),
            ),
          ],
        ),
      );

  Widget _buildCPFTotal() {
    return Container(
      padding: EdgeInsets.only(top: 14, bottom: 14, left: 20, right: 22),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: aceGrayColor,
            width: getDp(0.5),
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            S.current.total_cpf_contribution,
            style: TextStyle(fontSize: 15, color: aceBlackColor),
          ),
          listBuilder<num>(
            selector: (_, __) => __.cpfTotal,
            builder: (BuildContext context, num value, Widget child) => Text(
              value.toStringAsNotFixed(2),
              style: TextStyle(fontSize: 15, color: aceBlackColor),
            ),
          )
        ],
      ),
    );
  }

  Widget _buildGrandTotal() {
    return Container(
      padding: EdgeInsets.only(top: 14, bottom: 14, left: 20, right: 22),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            S.current.grand_total,
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w700,
                color: aceDarkGrayColor),
          ),
          Text(
            provider.grandTotal.toStringAsFixed(2),
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w700,
                color: aceDarkGrayColor),
          ),
        ],
      ),
    );
  }

  Widget _buildYearMonthWidget() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: getDp(35)),
      child: Row(
        children: [
          Expanded(
            child: listBuilder<DateTime>(
              selector: (_, __) => __.date,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  TimeSelectItem(
                      title: S.current.month,
                      value: value == null
                          ? Config.settingInfo.dateFormat.toUpperCase() ?? "MM"
                          : DateTimeUtils.formatMonth(value),
                      onTap: widget.data != null
                          ? null
                          : provider.onSelectYearMonth),
            ),
          ),
          SizedBox(
            width: getDp(13),
          ),
          Expanded(
            child: listBuilder<DateTime>(
              selector: (_, __) => __.date,
              builder: (BuildContext context, DateTime value, Widget child) =>
                  TimeSelectItem(
                      title: S.current.year,
                      value: value == null
                          ? Config.settingInfo.dateFormat.toUpperCase() ??
                              "YYYY"
                          : DateTimeUtils.formatYear(value),
                      onTap: widget.data != null
                          ? null
                          : provider.onSelectYearMonth),
            ),
          ),
        ],
      ),
    );
  }
}
